//
//  ShoppingCart_Root_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/10/30.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "ShoppingCart_Root_Controller.h"
//untils
#import "Global.h"
#import "UIColor+Hex.h"
#import "AppDelegate.h"
#import "UIImage+ColorToImage.h"
#import "ManagerGlobeUntil.h"
#import "FMDBManager.h"
#import "NSString+Conversion.h"
//view
#import "ShoppingCart_RootCell.h"
#import "ShoppingCartBottomView.h"
#import "EmptyPageView.h"
#import "ShoppingCartSectionHeaderView.h"
//controllers
#import "Strore_detailController.h"
#import "Login_Controller.h"
#import "Home_Root_Controller.h"
#import "MyGoodsSureOrderController.h"
//vendor
#import "MTA.h"
#import "RDVTabBarController.h"
//viewModel
#import "ShoppingCartViewModel.h"
@interface ShoppingCart_Root_Controller ()<UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource,ShopCarTableViewCellDelegate,EmptyPageViewDelegate>{
    BOOL _isEditStatus;
}
//viewModel
@property(nonatomic, strong)ShoppingCartViewModel *viewModel;
//view
@property(strong,nonatomic)EmptyPageView *emptyView;
@property(strong,nonatomic)UITableView *tableView;
@property(nonatomic, strong)ShoppingCartBottomView *bottomView;
@property(strong,nonatomic)UIView *clearview;//bottom下面视图，为了凸显透明效果
//data
@property (nonatomic,strong)NSIndexPath *indexPath;//记录加减号 cell的indexpath
@property(nonatomic, strong)NSMutableArray *dataSource;
@end

@implementation ShoppingCart_Root_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    self.view.backgroundColor=[UIColor colorWithHexString:@"#efefef"];
    _dataSource = [[NSMutableArray alloc]init];
    [self setupSubView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self addRightNavItemWithTitle:@"编辑"];
    _isEditStatus = NO;
    [self.viewModel requestShoppingCartDatas:^(NSArray *goodsData) {
        [self updateTableViewWithDatas:goodsData];
    }];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"购物车"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"购物车"];
}
#pragma mark--  UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[self.dataSource objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    ShoppingCart_RootCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[ShoppingCart_RootCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.delegate = self;
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    cell.indexPath = indexPath;
    NSDictionary *dataDic = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [cell settingDataWithdicData:dataDic];
    return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.viewModel deleteGoodsAtIndexPath:indexPath success:^(NSArray *goodsData) {
            [self updateTableViewWithDatas:goodsData];
        }];
    }
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return HightScalar(147);
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HightScalar(50);
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.dataSource.count != (section+1)) {
        return HightScalar(12);
    }
    return 0.1;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    CGFloat sectionHight = 0.1;
    if (self.dataSource.count != (section+1)) {
        sectionHight = HightScalar(12);
    }
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, sectionHight)];
    view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    return view;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ShoppingCartSectionHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"Header"];
    if (!headerView) {
        headerView = [[ShoppingCartSectionHeaderView alloc] initWithReuseIdentifier:@"Header"];
    }
    headerView.section = section;
    headerView.delegate = (id<ShoppingCartSectionHeaderViewDelegate>)self;
    [headerView updateViewWithShoppingCartSectionHeaderModel:[self.viewModel.sectionHeaderDatasArr objectAtIndex:section]];
    return  headerView;
}

//侧滑删除
-(nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!_isEditStatus) {//未编辑状态可以跳转
        Strore_detailController *detailVC = [[Strore_detailController alloc]init];
        NSDictionary *dataDic = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        detailVC.goodsID = [NSString stringTransformObject:[dataDic objectForKey:@"goodID"]];
        detailVC.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"isProprietary"]];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
#pragma mark-- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1) {//多选删除
        if (buttonIndex == 1) {//删除全部
            if (self.bottomView.isAllSelected) {
                //删除全部
                [[FMDBManager sharedManager]deleteAll:@"t_shopCar"];
                [self showNoDataPage];
            } else {//删除选中数据
                [self.viewModel deleteSelectedGoodsSuccess:^(NSArray *goodsData) {
                    [self updateTableViewWithDatas:goodsData];
                }];
            }
        }
        
    }else if (alertView.tag == 2) {//删除单个商品
        if (buttonIndex == 1) {
            [self.viewModel deleteGoodsAtIndexPath:self.indexPath success:^(NSArray *goodsData) {
                [self updateTableViewWithDatas:goodsData];
            }];
        }
    }
}
#pragma mark -- ShoppingCartSectionHeaderViewDelegate 购物车sectionheader 
-(void)selectSectionHeaderWithGoodsType:(NSInteger)goodsType viewForHeaderInSection:(NSInteger)section isSelected:(BOOL)isSelected {
    [self.viewModel updateSectionDataWithSelectSectionHeaderWithGoodsType:goodsType viewForHeaderInSection:section isSelected:isSelected success:^(NSArray *goodsData) {
        [self updateTableViewWithDatas:goodsData];
    }];
}
#pragma mark -- DetailViewCellDelegate 购物车cell
//选中商品或者取消选中商品
- (void)selectedItemAtIndexPath:(NSIndexPath*)indexPath selected:(BOOL)isSelected {
    [self.viewModel updateCellDataWithSelectedCellIndexPath:indexPath isSelected:isSelected success:^(NSArray *goodsData) {
        [self updateTableViewWithDatas:goodsData];
    }];
}
//商品数量增加或减少
- (void)selectedItemAtIndexPath:(NSIndexPath *)indexPath tag:(NSInteger)tag{
    self.indexPath = indexPath;
    NSDictionary *dataDic = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSInteger goodsCount = [[dataDic objectForKey:@"buynum"] integerValue];
    if (tag == 11) {//数量减少
        if (goodsCount == 1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除该商品？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag =2;
            [alert show];
            return ;
        }
        goodsCount--;
        if (goodsCount <= 1) {
            goodsCount = 1;
        }
    }else{//数量增加
        goodsCount ++;
    }
    [self.viewModel updateCellDataWithSelectedCellIndexPath:indexPath goodsCount:goodsCount success:^(NSArray *goodsData) {
        [self updateTableViewWithDatas:goodsData];
    }];
}

#pragma mark -- ShoppingCartBottomViewDelegate
//是否选中全部商品
- (void)selectedAllProductsWithSelectedStatus:(BOOL)isSelected{
    [self.viewModel updateAllDataWithSelectedStatus:isSelected success:^(NSArray *goodsData) {
        [self updateTableViewWithDatas:goodsData];
    }];
}
//去结算
- (void)goJieSuan {
    XiaoQuAndStoreInfoModel *model =[[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    //选中便利店商品
    NSMutableArray *storeGoodsArr =[[FMDBManager sharedManager]QueryIsChoosedDataInShopWithShopID:[NSString stringISNull:model.storeID]];
    //选中自营商品
    NSMutableArray *selfGoodsArr = [[FMDBManager sharedManager]QueryisProprietaryIsChoosedData];
    if ([ManagerGlobeUntil sharedManager].transactionLogin) {//已经登陆
        if (model.storeID.integerValue != kDaShiHuiStoreID) {
            if (storeGoodsArr.count!=0 || selfGoodsArr.count != 0) {//只有选中商品才跳转
                MyGoodsSureOrderController *sureOrderVC = [[MyGoodsSureOrderController alloc]init];
                sureOrderVC.storeGoodsArr = storeGoodsArr;
                sureOrderVC.selfGoodsArr = selfGoodsArr;
                [self.navigationController pushViewController:sureOrderVC animated:YES];
            }else{//未选中商品进行提示
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"您还没有选择商品哦!" inView:self.view];
            }
        } else {//大实惠总部店不可以下单
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"您所在的小区暂未开通服务，敬请期待！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
        }
    } else {//未登陆
        Login_Controller *loginVC = [[Login_Controller alloc]init];
        loginVC.supperControllerType = kShoppingCartGoToJieSuanPushToLogin_ControllerSupperController;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
}
//添加关注
- (void)addGuanZhu {
    if ([ManagerGlobeUntil sharedManager].transactionLogin) {//已经登陆
        [self.viewModel markGoodsSuccess:^(NSString *successMsg) {
            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:successMsg inView:self.view];
        } failure:^(NSString *failureMessage) {
            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
        }];
    } else {//未登陆
        Login_Controller *loginVC = [[Login_Controller alloc]init];
        loginVC.supperControllerType = kShoppingCartGoToJieSuanPushToLogin_ControllerSupperController;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
}
//删除商品
- (void)deleteProduct {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableArray *dataSource =[[FMDBManager sharedManager]QueryIsChoosedDataWithShopID:[NSString stringISNull:mode.storeID]];
    [dataSource addObjectsFromArray:[[FMDBManager sharedManager]QueryisProprietaryIsChoosedData]];
    if (dataSource.count!=0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag=1;
        [alert show];
    }else {
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"您还没有选择商品" inView:self.view];
    }
}
#pragma mark -- butotn action
-(void)rigthBtnAction:(id)sender {
    UIButton *button = (UIButton*)sender;
    button.selected = !button.selected;
    [button setTitle:button.selected ? @"完成" : @"编辑" forState:UIControlStateNormal];
    [self updateBottomViewWithEditStatus:button.selected];
}
//立即逛逛 跳转
-(void)buttonClick
{
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    Home_Root_Controller *homeVC = [[[appDelegate.tabBarController.viewControllers firstObject] childViewControllers] firstObject];
    [homeVC.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
    [appDelegate selectedControllerAtTabBarIndex:0];
}
#pragma mark -- 给视图进行赋值
- (void)updateBottomViewWithEditStatus:(BOOL)isEdit {
  [self.bottomView changeSubViewShowWithEditStatus:isEdit];
  self.bottomView.isAllSelected = self.viewModel.bottomModel.isSelected;
    _isEditStatus = isEdit ? YES : NO;
    if (!isEdit) {
        self.bottomView.totalPrice = self.viewModel.bottomModel.totalPrice;
        self.bottomView.productCount = self.viewModel.bottomModel.goodsCount;
    }
}
- (void)showNoDataPage {
    self.bottomView.isAllSelected = NO;
    self.emptyView.hidden=NO;
    self.tableView.hidden=YES;
    self.bottomView.hidden=YES;
    self.clearview.hidden = YES;
    [self addRightNavItemWithTitle:@"编辑"];
    self.navigationItem.rightBarButtonItem.enabled=NO;
}
- (void)showTableView {
    self.emptyView.hidden=YES;
    self.tableView.hidden=NO;
    self.bottomView.hidden=NO;
    self.clearview.hidden = NO;
    self.navigationItem.rightBarButtonItem.enabled=YES;
}
- (void)updateTableViewWithDatas:(NSArray*)goodsData {
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:goodsData];
    if (self.dataSource.count == 0) {
        [self showNoDataPage];
    } else {
        [self showTableView];
        [self.tableView reloadData];
        [self updateBottomViewWithEditStatus:_isEditStatus];
    }
}
#pragma mark -- 初始化视图
- (void)setupSubView {
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.emptyView];
    [self.view addSubview:self.clearview];
    [self.view addSubview:self.bottomView];
}
#pragma mark -- getter Method
- (UITableView*)tableView {
    if (!_tableView) {
        CGRect tableFrame = CGRectMake(0, 0,VIEW_WIDTH , VIEW_HEIGHT-64-49);
        _tableView =[[UITableView alloc]initWithFrame:tableFrame style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor = [UIColor whiteColor];
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, HightScalar(12))];
        headerView.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
        _tableView.tableHeaderView = headerView;
        UIView *footview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 49)];
        _tableView.tableFooterView=footview;
    }
    return _tableView;
}

- (EmptyPageView*)emptyView {
    if (!_emptyView) {
        _emptyView =[[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0,VIEW_WIDTH , VIEW_HEIGHT-64-49)
                                      EmptyPageViewType:kShoppingCarView];
        _emptyView.backgroundColor=[UIColor whiteColor];
        _emptyView.hidden=YES;
        _emptyView.delegate =self;
    }
    return _emptyView;
}
- (UIView*)clearview {
    if (!_clearview) {
        _clearview=[[UIView alloc]init];
        _clearview.frame = CGRectMake(0, CGRectGetMaxY(_tableView.frame)-49, CGRectGetWidth(_tableView.bounds), 49);
        _clearview.alpha=0.6;
        _clearview.backgroundColor=[UIColor blackColor];
    }
    return _clearview;
}
- (ShoppingCartBottomView*)bottomView {
    if (!_bottomView) {
        _bottomView = [[ShoppingCartBottomView alloc]initWithFrame:self.clearview.frame withEditStatus:NO];
        _bottomView.delegate = (id<ShoppingCartBottomViewDelegate>)self;
        _bottomView.backgroundColor = [UIColor clearColor];
    }
    return _bottomView;
}
- (ShoppingCartViewModel*)viewModel {
    if (!_viewModel) {
        _viewModel = [[ShoppingCartViewModel alloc]init];
    }
    return _viewModel;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
